import org.springframework.web.multipart.commons.CommonsMultipartFile
import util.IdGenerator
import jxl.*

class UploadService {

    boolean transactional = true

    def idGenerator = new IdGenerator()

    def uploadExcel(CommonsMultipartFile file) {

        Workbook workbook = Workbook.getWorkbook(file.inputStream)
        Sheet sheet = workbook.getSheet(0)

        for (int r = 1; r < sheet.rows; r++) {
            def productName = sheet.getCell(0, r).contents

            def amount = sheet.getCell(1, r).contents

            def inPrice = sheet.getCell(2, r).contents

            def modelNo = sheet.getCell(3, r).contents

            def outPrice = sheet.getCell(4, r).contents

            def supplierName = sheet.getCell(5, r).contents
            def supplierId = supplierName.substring(11)
            // 得到供应商对象
            def supplier = Supplier.findById(supplierId)

            def catalogName = sheet.getCell(6,r).contents
            def catalogId = catalogName.substring(10)
            // 得到产品分类信息
            def catalog = Catalog.findById(catalogId)

            // 进货时间
            def time = new Date()

            def number = "进货号"+idGenerator.getId()

            def product = new ImportProduct(productName:productName,amount:amount,inPrice:inPrice,modelNo:modelNo,outPrice:outPrice,time:time,number:number)

            supplier.addToProducts(product)
            catalog.addToProducts(product)
            supplier.save(flush:true)
            catalog.save(flush:true)
        }

        workbook.close()

    }
}
